﻿using NewLife;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using XCode;
using XCode.Configuration;
using XCode.DataAccessLayer;
using Zdap.Common;
using Zdap.Common.AutoMapper;
using Zdap.Common.Extensions;
using Zdap.Common.IdGenerate;

namespace Zdap.XCode.Service
{
    /// <summary>
    /// </summary>
    public static class CommonService
    {
        /// <summary>
        ///
        /// </summary>
        public class CommonColumns
        {
            internal const string Id = "Id";
            internal const string CreateTime = "CreateTime";
            internal const string UpdateTime = "UpdateTime";
            internal const string IsDelete = "IsDelete";
            internal const string CreateBy = "CreateBy";
            internal const string UpdateBy = "UpdateBy";
            internal const string TenantId = "TenantId";
            internal const string ParentId = "ParentId";
        }

        //忽略的列
        private static string[] ignoreColumn = { CommonColumns.Id, CommonColumns.CreateTime, CommonColumns.UpdateTime, CommonColumns.IsDelete, CommonColumns.CreateBy, CommonColumns.UpdateBy };

        //忽略的列 的 规则 模糊匹配
        private static string[] ignoreColumnLike = { };

        // 对象的 列 缓存
        private static ConcurrentDictionary<string, List<ColumnDataModel>> columnDataDic = new ConcurrentDictionary<string, List<ColumnDataModel>>();

        // 对象的查询 列 缓存
        private static ConcurrentDictionary<string, string> selectDic = new ConcurrentDictionary<string, string>();

        /// <summary>
        ///
        /// </summary>
        public const string AllowNoParameter = "#A_N_Params#";//允许无参数，查询整个表的数据

        /// <summary>
        ///
        /// </summary>
        private const string where_between = "between#";//between 的特殊参数 标签

        /// <summary>
        /// 排除指定数据
        /// </summary>
        private const string unequal_to = "unequalto";

        /// <summary>
        /// 条件  or like
        /// </summary>
        private const string where_or = "where_or";

        /// <summary>
        /// 条件  or
        /// </summary>
        private const string where_or_and = "where_or_and";

        /// <summary>
        /// 设置 TEntity 通用字段
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static long SetCommonProperty<T>(T entity, UserTicket user) where T : Entity<T>, new()
        {
            SetCreateTime(entity);
            SetUpdateTime(entity);
            if (user != null)
            {
                SetCreateBy(entity, user.Id);
                SetUpdateBy(entity, user.Id);
                SetTenantId(entity, user.TenantId);
            }
            SetIsDelete(entity);
            return SetId(entity);
        }

        /// <summary>
        /// 设置 TEntity 通用字段
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static long SetCommonPropertyTenantId<T>(T entity, UserTicket user) where T : Entity<T>, new()
        {
            SetCreateTime(entity);
            SetUpdateTime(entity);
            if (user != null)
            {
                SetCreateBy(entity, user.Id);
                SetUpdateBy(entity, user.Id);
                SetTenantId(entity, user.TenantId, true);
            }
            SetIsDelete(entity);
            return SetId(entity);
        }

        /// <summary>
        /// 设置 Update 跟新时间跟新人 通用字段
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static void SetUpdateProperty<T>(T entity, UserTicket user) where T : Entity<T>, new()
        {
            SetUpdateTime(entity);
            if (user != null)
            {
                SetUpdateBy(entity, user.Id);
            }
        }

        /// <summary>
        /// 判断小于0 或等于=0 赋值新 id
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static long SetId<T>(T entity) where T : Entity<T>, new()
        {
            Type type = entity.GetType();
            PropertyInfo pi = type.GetProperty(CommonColumns.Id, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

            if (pi == null) throw new Exception("主键设置错误。");

            var idAny = pi.GetValue(entity);
            if (idAny.ToLong() > 0)
                return idAny.ToLong();
            else
            {
                long Id = IdWorker.NextId();
                pi.SetValue(entity, Id);
                return Id;
            }
        }

        /// <summary>
        /// 获取全路径
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static string GetPath<T>(T entity) where T : Entity<T>, new()
        {
            Type type = entity.GetType();
            PropertyInfo pi = type.GetProperty("Path");
            if (pi == null) return null;
            var idAny = pi.GetValue(entity);
            if (idAny != null)
                return idAny.ToString();
            else
                return "";
        }

        /// <summary>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="entity"></param>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static TValue SetProperty<T, TValue>(T entity, string propertyName, TValue value) where T : Entity<T>, new()
        {
            if (entity == null) return value;

            Type type = entity.GetType();
            PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if (pi != null)
                pi.SetValue(entity, value);
            return value;
        }

        /// <summary>
        /// 设置时间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="name"></param>
        public static void SetCreateTime<T>(T entity) where T : Entity<T>, new()
        {
            SetProperty(entity, CommonColumns.CreateTime, DateTime.Now);
        }

        /// <summary>
        /// 设置更新时间
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public static void SetUpdateTime<T>(T entity) where T : Entity<T>, new()
        {
            SetProperty(entity, CommonColumns.UpdateTime, DateTime.Now);
        }

        /// <summary>
        /// 设置创建人
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="userId"></param>
        public static void SetCreateBy<T>(T entity, long userId) where T : Entity<T>, new()
        {
            SetProperty(entity, CommonColumns.CreateBy, userId);
        }

        /// <summary>
        /// 设置父级节点
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="parentId"></param>
        public static void SetParentId<T>(T entity, long parentId) where T : Entity<T>, new()
        {
            SetProperty(entity, CommonColumns.ParentId, parentId);
        }

        /// <summary>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="Id"></param>
        public static void SetPath<T>(T entity, string Id) where T : Entity<T>, new()
        {
            SetProperty(entity, "Path", Id + ",");
        }

        /// <summary>
        /// 设置更新人Id
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="userId"></param>
        public static void SetUpdate<T>(T entity, long userId) where T : Entity<T>, new()
        {
            SetUpdateBy(entity, userId);
            SetUpdateTime(entity);
            SetIsDelete(entity, 0);
        }

        /// <summary>
        /// 设置更新人Id
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="userId"></param>
        public static void SetUpdateBy<T>(T entity, long userId) where T : Entity<T>, new()
        {
            SetProperty(entity, CommonColumns.UpdateBy, userId);
        }

        /// <summary>
        /// 设置租户Id
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="tenantId"></param>
        public static void SetTenantId<T>(T entity, long tenantId) where T : Entity<T>, new()
        {
            string name = CommonColumns.TenantId;
            Type type = entity.GetType();
            PropertyInfo pi = type.GetProperty(name);
            if (pi != null)
            {
                var id = pi.GetValue(entity).ToLong();
                if (id == 0)//如果没有单独赋值，就设置值
                {
                    pi.SetValue(entity, tenantId);
                }
            }
        }

        /// <summary>
        /// 设置租户Id
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="tenantId"></param>
        public static void SetTenantId<T>(T entity, long tenantId, bool a) where T : Entity<T>, new()
        {
            string name = CommonColumns.TenantId;
            Type type = entity.GetType();
            PropertyInfo pi = type.GetProperty(name);
            if (pi != null)
            {
                var id = pi.GetValue(entity).ToLong();
                if (a)
                {
                    pi.SetValue(entity, tenantId);
                }
                else if (id == 0)//如果没有单独赋值，就设置值
                {
                    pi.SetValue(entity, tenantId);
                }
            }
        }

        /// <summary>
        /// 设置删除 默认：1 删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public static void SetIsDelete<T>(T entity, int isDelete = 0) where T : Entity<T>, new()
        {
            string name = CommonColumns.IsDelete;
            SetProperty(entity, name, isDelete);
        }

        /// <summary>根据条件 更新数据 </summary>
        /// <param name="setNames">更新属性列表</param>
        /// <param name="setValues">更新值列表</param>
        /// <param name="whereNames">条件属性列表</param>
        /// <param name="whereValues">条件值列表</param>
        /// <returns>返回受影响的行数</returns>
        public static ResponseContext<bool> Update<TEntity>(List<string> setNames, List<Object> setValues, List<String> whereNames, List<Object> whereValues, UserTicket user = null) where TEntity : Entity<TEntity>, new()
        {
            var result = new ResponseContext<bool>();

            if (user != null && CheckField<TEntity>(CommonColumns.UpdateBy))
            {
                setNames.Add(CommonColumns.UpdateBy);
                setValues.Add(user.Id);
            }
            if (CheckField<TEntity>(CommonColumns.UpdateTime))
            {
                setNames.Add(CommonColumns.UpdateTime);
                setValues.Add(DateTime.Now);
            }

            Entity<TEntity>.Update(setNames.ToArray(),
                setValues.ToArray(),
                whereNames.ToArray(),
                whereValues.ToArray());

            return result.SetSuccess(true);
        }

        /// <summary>
        /// 按条件删除 逻辑删除
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static ResponseContext<bool> DeleteLogic<TEntity>(IDictionary<string, object> param, UserTicket user) where TEntity : Entity<TEntity>, new()
        {
            var result = new ResponseContext<bool>();
            var updateField = new List<string>();// 更新的字段
            var updateField_V = new List<object>();// 更新的字段 对应的值
            var updateField_W = new List<string>();//更新 查询条件字段
            var updateField_W_V = new List<object>();//更新 查询条件字段 对应的值
            if (!CheckField<TEntity>(CommonColumns.IsDelete))
            {
                return result.SetError($"无法使用逻辑删除，{typeof(TEntity).FullName}中没有字段逻辑删除字段");
            }
            updateField.Add(CommonColumns.IsDelete);
            updateField_V.Add(CommonConstants.IsDelete);
            if (CheckField<TEntity>(CommonColumns.UpdateBy))
            {
                updateField.Add(CommonColumns.UpdateBy);
                updateField_V.Add(user.Id);
            }
            if (CheckField<TEntity>(CommonColumns.UpdateTime))
            {
                updateField.Add(CommonColumns.UpdateTime);
                updateField_V.Add(DateTime.Now);
            }
            foreach (var item in param.Keys)
            {
                if (!CheckField<TEntity>(item))
                    return result.SetError($"字段不存在，{typeof(TEntity).FullName}中没有{item}字段");
                updateField_W.Add(item);
                updateField_W_V.Add(param[item]);
            }

            Entity<TEntity>.Update(updateField.ToArray(),
                updateField_V.ToArray(),
                updateField_W.ToArray(),
                updateField_W_V.ToArray());

            return result.SetSuccess(true);
        }

        /// <summary>
        /// 按条件删除 逻辑删除 先查询出来在update
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static ResponseContext<bool> DeleteLogic_Find<TEntity>(IDictionary<string, object> param, UserTicket user) where TEntity : Entity<TEntity>, new()
        {
            var result = new ResponseContext<bool>();
            var where = BuildWhereExpression<TEntity>(param);
            var entitys = Entity<TEntity>.FindAll(where);

            foreach (var entity in entitys)
            {
                SetIsDelete(entity, CommonConstants.IsDelete);
                SetUpdateBy(entity, user.Id);
                SetUpdateTime(entity);
            }
            entitys.Update();

            return result.SetSuccess(true);
        }

        /// <summary>
        /// 构建查询条件
        /// </summary>
        /// <param name="param"></param>
        /// <param name="ignore">忽略是否构建有效的 where 条件检查</param>
        /// <returns></returns>
        public static WhereExpression BuildWhereExpression<TEntity>(IDictionary<string, object> param, bool ignore = false) where TEntity : Entity<TEntity>, new()
        {
            var whereExpression = new WhereExpression();
            int i = 0;
            if (param == null || param.Keys.Count == 0)
                throw new ArgumentException("接口调用传参问题：Params 参数不能为空。");

            foreach (var item in param)
            {
                if (item.Key == where_between)// between
                {
                    whereExpression &= WhereExpressionDateBetweenAnd<TEntity>(item.Value.ToString());
                    i++;
                    continue;
                }

                //排除，不等于
                if (item.Key == unequal_to)
                {
                    whereExpression &= WhereExpressionDateUnequalTo<TEntity>(item.Value.ToString());
                    i++;
                    continue;
                }
                //or
                if (item.Key == where_or)
                {
                    whereExpression |= WhereExpressionDateWhere_or<TEntity>(item.Value.ToString());
                    i++;
                    continue;
                }
                //or
                if (item.Key == where_or_and)
                {
                    whereExpression |= WhereExpressionDateWhere_Or_And<TEntity>(item.Value.ToString());
                    i++;
                    continue;
                }

                var field = Entity<TEntity>.Meta.Table.FindByName(item.Key);
                if (string.IsNullOrEmpty(field) || field.Column == null)
                {
                    continue;//如果参数名称 不是表中的字段名称 将忽略
                }

                if (item.Value != null && item.Value != string.Empty)
                {
                    whereExpression = WhereExpressionCommon(whereExpression, item, field);
                    i++;
                }
            }
            // ignore 忽略必须构建的方式
            if (!ignore && i == 0)//检测到传入的参数构建查询条件，没有符合要求的，即：构建的查询条件为空
            {
                var allowNoParameter = false;//查询条件是否可以为空
                if (param.ContainsKey(AllowNoParameter))
                {
                    if (param.TryGetValue(AllowNoParameter, out var allowNoParameter2))
                    {
                        allowNoParameter = Convert.ToBoolean(allowNoParameter2);
                    }
                }
                if (!allowNoParameter)//查询条件不允许为空
                    throw new ArgumentException($"接口调用传参问题：构建的查询条件为空，请检查 Params 中每个参数赋值是否有效或正确，null或者空字符串视为无效值。");
            }

            // 需要查指定删除的题
            param.TryGetValue(CommonColumns.IsDelete, out var _isDelete);

            if (_isDelete == null)
            {
                //增加 过滤掉 已删除的数据 的查询条件
                var dfield = Entity<TEntity>.Meta.Table.FindByName(CommonColumns.IsDelete);
                if (!string.IsNullOrEmpty(dfield) && dfield.Column != null)
                {
                    whereExpression &= dfield == CommonConstants.IsNotDelete;
                }
            }

            return whereExpression;
        }

        /// <summary>
        /// 构建  条件 or
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="paramValue"></param>
        /// <returns></returns>
        public static WhereExpression WhereExpressionDateWhere_or<TEntity>(string paramValue) where TEntity : Entity<TEntity>, new()
        {
            var whereExpression = new WhereExpression();
            var param = paramValue.ToObject<IDictionary<string, string>>();
            foreach (var item in param)
            {
                var field = Entity<TEntity>.Meta.Table.FindByName(item.Key);
                if (string.IsNullOrEmpty(field) || string.IsNullOrEmpty(field.ColumnName))
                    continue; //如果参数名称 不是表中的字段名称 将忽略
                if (item.Value != null && item.Value.Count() > 0)
                {
                    whereExpression |= field.Contains(item.Value.ToString());   // 不等于
                }
            }
            return whereExpression;
        }

        /// <summary>
        /// 构建  条件 or
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="paramValue"></param>
        /// <returns></returns>
        public static WhereExpression WhereExpressionDateWhere_Or_And<TEntity>(string paramValue) where TEntity : Entity<TEntity>, new()
        {
            var whereExpression = new WhereExpression();
            var param = paramValue.ToObject<IDictionary<string, string>>();
            foreach (var item in param)
            {
                var field = Entity<TEntity>.Meta.Table.FindByName(item.Key);
                if (string.IsNullOrEmpty(field) || string.IsNullOrEmpty(field.ColumnName))
                    continue; //如果参数名称 不是表中的字段名称 将忽略
                if (item.Value != null && item.Value.Count() > 0)
                {
                    whereExpression |= field == item.Value.ToString();   // 等于
                }
            }
            return whereExpression;
        }

        /// <summary>
        /// 构建查询条件
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        //public static WhereExpression BuildWhereExpression<TEntity>(IDictionary<string, object> param) where TEntity : Entity<TEntity>, new()
        //{
        //    var whereExpression = new WhereExpression();
        //    int i = 0;
        //    if (param == null || param.Keys.Count == 0)
        //        throw new ArgumentException("接口调用传参问题：Params 参数不能为空。");

        //    foreach (var item in param)
        //    {
        //        if (item.Key == where_between)// between
        //        {
        //            whereExpression &= WhereExpressionDateBetweenAnd<TEntity>(item.Value.ToString());
        //            i++;
        //            continue;
        //        }
        //        var field = Entity<TEntity>.Meta.Table.FindByName(item.Key);
        //        if (string.IsNullOrEmpty(field) || field.Column == null)
        //        {
        //            continue;//如果参数名称 不是表中的字段名称 将忽略
        //        }

        //        if (item.Value != null && item.Value != string.Empty)
        //        {
        //            whereExpression = WhereExpressionCommon(whereExpression, item, field);
        //            i++;
        //        }
        //    }

        //    if (i == 0)//检测到传入的参数构建查询条件，没有符合要求的，即：构建的查询条件为空
        //    {
        //        var allowNoParameter = false;//查询条件是否可以为空
        //        if (param.ContainsKey(AllowNoParameter))
        //        {
        //            if (param.TryGetValue(AllowNoParameter, out var allowNoParameter2))
        //            {
        //                allowNoParameter = Convert.ToBoolean(allowNoParameter2);
        //            }
        //        }
        //        if (!allowNoParameter)//查询条件不允许为空
        //            throw new ArgumentException($"接口调用传参问题：构建的查询条件为空，请检查 Params 中每个参数赋值是否有效或正确，null或者空字符串视为无效值。");
        //    }

        //    // 需要查指定删除的题
        //    param.TryGetValue( CommonColumns.IsDelete, out var _isDelete);

        //    if (_isDelete == null)
        //    {
        //        //增加 过滤掉 已删除的数据 的查询条件
        //        var dfield = Entity<TEntity>.Meta.Table.FindByName( CommonColumns.IsDelete);
        //        if (!string.IsNullOrEmpty(dfield) && dfield.Column != null)
        //        {
        //            whereExpression &= dfield == Zdap.Common.CommonConstants.IsNotDelete;
        //        }
        //    }

        //    return whereExpression;
        //}

        /// <summary>
        /// 构建查询条件，通用数据类型
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <param name="item"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        private static WhereExpression WhereExpressionCommon(WhereExpression whereExpression, KeyValuePair<string, object> item, Field field)
        {
            if (field.Type.Name == typeof(string).Name)// 字符串 like 模糊查询
            {
                whereExpression &= field.Contains(item.Value.ToString());
            }
            else if (item.Value.GetType() == typeof(JArray))//如果参数传的是 数组，则转换成 in 查询
            {
                var temp = item.Value.ToString();
                if (temp != "[]")//不是空数组
                {
                    var array = temp.ToObject<string[]>();
                    if (array.Length > 0)
                    {
                        whereExpression &= field.In(array);
                    }
                }
            }
            else if (item.Value.GetType().IsArray || item.Value.GetType().IsGenericType && item.Value.GetType().GetInterfaces().Any(e => e == typeof(System.Collections.IEnumerable)))//如果参数传的是 数组，则转换成 in 查询
            {
                whereExpression &= field.In(item.Value as System.Collections.IEnumerable);
            }
            else
            {
                whereExpression &= field == item.Value;
            }

            return whereExpression;
        }

        /// <summary>
        /// 构建 不等于条件
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="paramValue"></param>
        /// <returns></returns>
        public static WhereExpression WhereExpressionDateUnequalTo<TEntity>(string paramValue) where TEntity : Entity<TEntity>, new()
        {
            var whereExpression = new WhereExpression();
            var param = paramValue.ToObject<IDictionary<string, string>>();
            foreach (var item in param)
            {
                var field = Entity<TEntity>.Meta.Table.FindByName(item.Key);
                if (string.IsNullOrEmpty(field) || string.IsNullOrEmpty(field.ColumnName)) continue; //如果参数名称 不是表中的字段名称 将忽略
                if (item.Value != null && item.Value.Count() > 0)
                {
                    whereExpression &= field != item.Value;  // 不等于等于
                }
                else if (item.Value.GetType() == typeof(JArray))//如果参数传的是 数组，则转换成 in 查询
                {
                    var temp = item.Value.ToString();
                    if (temp != "[]")//不是空数组
                    {
                        var array = temp.ToObject<string[]>();
                        if (array.Length > 0)
                        {
                            whereExpression &= field.NotIn(array);
                        }
                    }
                }
            }
            return whereExpression;
        }

        public static WhereExpression WhereExpressionDateBetweenAnd<TEntity>(string paramValue) where TEntity : Entity<TEntity>, new()
        {
            var whereExpression = new WhereExpression();
            //if (paramValue.IsNullOrEmpty())
            if (System.String.IsNullOrWhiteSpace(paramValue))
                return whereExpression;

            var param = paramValue.ToObject<IDictionary<string, List<string>>>();
            foreach (var item in param)
            {
                var field = Entity<TEntity>.Meta.Table.FindByName(item.Key);
                if (string.IsNullOrEmpty(field) || string.IsNullOrEmpty(field.ColumnName)) continue; //如果参数名称 不是表中的字段名称 将忽略
                if (item.Value != null && item.Value.Count() > 0)
                {
                    var start = item.Value[0];
                    if (start.IsNotNullAndWhiteSpace() && start != "0001-01-01 00:00:00" && start != "0000-00-00 00:00:00")//去掉无效时间： "0001-01-01 00:00:00"
                    {
                        whereExpression &= field >= start;  // 大于等于 0
                    }
                    //if (item.Value.Count > 1 && item.Value[1] > new DateTime())//去掉无效时间： "0001-01-01 00:00:00"
                    if (item.Value.Count > 1 && item.Value[1].IsNotNullAndWhiteSpace() && item.Value[1] != "0001-01-01 00:00:00" && item.Value[1] != "0000-00-00 00:00:00")//去掉无效时间： "0001-01-01 00:00:00"
                        whereExpression &= field < item.Value[1]; //小于 1
                }
            }
            return whereExpression;
        }

        public static bool CheckField<TEntity>(string field) where TEntity : Entity<TEntity>, new()
        {
            if (string.IsNullOrEmpty(field))
                return false;

            var field2 = Entity<TEntity>.Meta.Table.FindByName(field);
            if (string.IsNullOrEmpty(field2))
                return false;
            return true;
        }

        /// <summary>
        /// 查询所有数据 不分页
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static async Task<IList<TEntity>> SearchAll<TEntity>(RequestParameter p) where TEntity : Entity<TEntity>, new()
        {
            return await SearchAll<TEntity>(p.Params);
        }

        /// <summary>
        /// 查询所有数据 不分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static async Task<IList<TEntity>> SearchAll<TEntity>(IDictionary<string, object> param, string[] selects) where TEntity : Entity<TEntity>, new()
        {
            if (param == null && param.Count == 0)
                return null;

            var whereExpression = BuildWhereExpression<TEntity>(param);

            string orderBy = BuildOrderBy<TEntity>(param);

            string str_selects = null;
            if (selects.IsNotNullAndEmpty())
            {
                str_selects = string.Join(",", selects);
            }

            return await SearchAll<TEntity>(whereExpression, orderBy, str_selects);
        }

        /// <summary>
        /// 查询所有数据 不分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static async Task<IList<TEntity>> SearchAll<TEntity>(IDictionary<string, object> param, string selects = null) where TEntity : Entity<TEntity>, new()
        {
            if (param == null && param.Count == 0)
                return null;

            var whereExpression = BuildWhereExpression<TEntity>(param);

            string orderBy = BuildOrderBy<TEntity>(param);

            return await SearchAll<TEntity>(whereExpression, orderBy, selects);
        }

        /// <summary>
        /// 查询所有数据 不分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static async Task<IList<TEntity>> SearchAll<TEntity>(Expression whereExpression, string orderBy = null, string selects = null) where TEntity : Entity<TEntity>, new()
        {
            if (whereExpression == null)
                return null;

            var datas = await Entity<TEntity>.FindAllAsync(whereExpression, orderBy, selects, 0, 0);

            return datas;
        }

        /// <summary>
        /// 查询所有数据 不分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static async Task<IList<TModel>> SearchAll<TEntity, TModel>(RequestParameter p) where TModel : class where TEntity : Entity<TEntity>, new()
        {
            return await SearchAll<TEntity, TModel>(p.Params);
        }

        /// <summary>
        /// 查询所有数据 不分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="param"></param>
        /// <returns></returns>
        public static async Task<IList<TModel>> SearchAll<TEntity, TModel>(IDictionary<string, object> param) where TModel : class where TEntity : Entity<TEntity>, new()
        {
            string orderBy = BuildOrderBy<TEntity>(param);

            var whereExpression = BuildWhereExpression<TEntity>(param);

            return await SearchAll<TEntity, TModel>(whereExpression, orderBy);
        }

        /// <summary>
        /// 查询所有数据 不分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="whereExpression"></param>
        /// <param name="orderBy"></param>
        /// <param name="selects"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        //public static async Task<IList<TModel>> SearchAll<TEntity, TModel>(IDictionary<string, object> param, string selects = null) where TModel : class where TEntity : Entity<TEntity>, new()
        //{
        //    string orderBy = BuildOrderBy<TEntity>(param);
        //    var whereExpression = BuildWhereExpression<TEntity>(param);
        //    return await SearchAll<TEntity, TModel>(whereExpression, orderBy,selects);
        //}

        /// <summary>
        /// 查询所有数据 不分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="whereExpression"></param>
        /// <param name="orderBy"></param>
        /// <param name="selects"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static async Task<IList<TModel>> SearchAll<TEntity, TModel>(Expression whereExpression, string orderBy = null, string selects = null) where TModel : class where TEntity : Entity<TEntity>, new()
        {
            if (string.IsNullOrWhiteSpace(selects))
            {
                selects = GetSelectColumn<TEntity, TModel>();
            }
            var list = await SearchAll<TEntity>(whereExpression, orderBy, selects);

            if (list == null)
                return null;

            var datas = new List<TModel>();
            foreach (var item in list)
            {
                var dto = item.MapTo<TModel>();
                // 处理dto JOSN转string保存
                if (CommonService.IsJsonField(dto))
                {
                    LoadFieldsStringCovertJson(item, dto);
                }
                datas.Add(dto);
            }

            return datas;
        }

        /// <summary>
        /// 分页查询 分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static async Task<PageResponseContext2<TModel>> SearchAsync<TEntity, TModel>(Pager p) where TModel : class where TEntity : Entity<TEntity>, new()
        {
            var whereExpression = BuildWhereExpression<TEntity>(p.Params);//构建查询条件

            return await SearchAsync<TEntity, TModel>(whereExpression, p);
        }

        /// <summary>
        /// 分页查询 分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="whereExpression"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static async Task<PageResponseContext2<TModel>> SearchAsync<TEntity, TModel>(Expression whereExpression, Pager p) where TModel : class where TEntity : Entity<TEntity>, new()
        {
            var r = new PageResponseContext2<TModel>();
            if (whereExpression == null)
                return r.SetError("查询条件不能为空.");

            p.RetrieveTotalCount = true;//设置返回 总数
            if (string.IsNullOrWhiteSpace(p.OrderBy) && string.IsNullOrEmpty(p.Sort))
            {
                p.OrderBy = BuildDefaultOrderBy<TEntity>();
            }

            var select = GetSelectColumn<TEntity, TModel>();

            var list = await Entity<TEntity>.FindAllAsync(whereExpression, p, select);//从数据库中 分页查询符合条件的
            var datas = new List<TModel>();
            foreach (var item in list)// 转换成 Dto
            {
                var dto = item.MapTo<TModel>();
                // 处理dto JOSN转string保存
                if (CommonService.IsJsonField(dto))
                {
                    LoadFieldsStringCovertJson(item, dto);
                }
                datas.Add(dto);
            }

            if (p.ReturnColumn)//Model对象 的属性转换成 列头
            {
                r.ColumnDatas = GetColumnDataModel<TEntity, TModel>();
            }
            return r.SetSuccess(datas, p);
        }

        /// <summary>
        /// 根据 Id 查询 对象
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static async Task<TEntity> FindById<TEntity>(long Id) where TEntity : Entity<TEntity>, new()
        {
            var field = Entity<TEntity>.Meta.Table.FindByName("Id");
            var where = field == Id;

            var isDelete = Entity<TEntity>.Meta.Table.FindByName(CommonColumns.IsDelete);
            if (isDelete?.Name != null)
                where &= isDelete == CommonConstants.IsNotDelete;

            var entity = await Entity<TEntity>.FindAsync(where);

            return entity;
        }

        /// <summary>
        /// 根据 Id 查询 对象
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static async Task<TModel> FindById<TEntity, TModel>(long Id) where TEntity : Entity<TEntity>, new() where TModel : class
        {
            var entity = await FindById<TEntity>(Id);

            if (entity == null)
                return null;
            var dto = entity.MapTo<TModel>();
            if (CommonService.IsJsonField(entity))
            {
                CommonService.LoadFieldsStringCovertJson(entity, dto);
            }
            return dto;
        }

        /// <summary>
        /// 根据 条件 查询 单个对象
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public static async Task<TEntity> FindBy<TEntity>(Expression whereExpression) where TEntity : Entity<TEntity>, new()
        {
            var entity = await Entity<TEntity>.FindAsync(whereExpression);

            return entity;
        }

        /// <summary>
        /// 根据 条件 查询 单个对象
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="param"></param>
        /// <returns></returns>
        public static async Task<TEntity> FindBy<TEntity>(IDictionary<string, object> param) where TEntity : Entity<TEntity>, new()
        {
            if (param == null && param.Count == 0)
                return null;

            var whereExpression = BuildWhereExpression<TEntity>(param);

            var entity = await Entity<TEntity>.FindAsync(whereExpression);

            return entity;
        }

        /// <summary>
        /// 根据 条件 查询 单个对象
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="param"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static async Task<TModel> FindBy<TEntity, TModel>(IDictionary<string, object> param) where TModel : class where TEntity : Entity<TEntity>, new()
        {
            var entity = await FindBy<TEntity>(param);

            if (entity == null)
                return null;
            var dto = entity.MapTo<TModel>();

            if (CommonService.IsJsonField(entity))
            {
                CommonService.LoadFieldsStringCovertJson(entity, dto);
            }
            return dto;
            //return entity.MapTo<TModel>();
        }

        /// <summary>
        /// 根据 条件 查询 单个对象
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public static async Task<TModel> FindBy<TEntity, TModel>(Expression whereExpression) where TModel : class where TEntity : Entity<TEntity>, new()
        {
            var entity = await FindBy<TEntity>(whereExpression);

            if (entity == null)
                return null;

            var dto = entity.MapTo<TModel>();

            if (CommonService.IsJsonField(entity))
            {
                CommonService.LoadFieldsStringCovertJson(entity, dto);
            }
            return dto;
        }

        /// <summary>
        /// 获取 Model对象 的属性转换成 列头
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <returns></returns>
        public static List<ColumnDataModel> GetColumnDataModel<TEntity, TModel>() where TModel : class where TEntity : Entity<TEntity>, new()
        {
            List<ColumnDataModel> columns;

            Type type = typeof(TModel);
            var key = type.FullName;
            var infos = type.GetProperties();

            var r = columnDataDic.TryGetValue(key, out columns);

            if (r && columns != null && columns.Count > 0)
                return columns;

            columns = new List<ColumnDataModel>();

            foreach (var item in infos)
            {
                //是否忽略
                if (IgnoreProp(item.Name)) continue;

                //在Dto 的属性中中添加 TableColumnAttribute 特性 控制 返回列头，如果没有就获取数据库实体中的
                DescriptionAttribute dattribute = null;
                var jsonIgnore = item.GetCustomAttribute<Newtonsoft.Json.JsonIgnoreAttribute>(true);
                var ttattribute = item.GetCustomAttribute<TableHeadAttribute>(true);
                if (ttattribute == null)
                    dattribute = item.GetCustomAttribute<DescriptionAttribute>(true);

                if (jsonIgnore != null || ttattribute != null && ttattribute.IsShow == 0)// 忽略
                {
                    continue;
                }
                else if (ttattribute != null && ttattribute.IsShow == 1)
                {
                    var column = CreateColumnData(item, "", ttattribute);
                    columns.Add(column);
                }
                else if (dattribute != null)
                {
                    var column = CreateColumnData(item, dattribute.Description, ttattribute);
                    columns.Add(column);
                }
                else//如果改字段在 Model 中没有设置中文描述，就从数据库定义中获取中文描述
                {
                    var fields = Entity<TEntity>.Meta.AllFields;
                    var o = fields.Find(x => x.Name == item.Name);

                    if (o == null) continue;

                    var column = CreateColumnData(item, o.Description, ttattribute);
                    columns.Add(column);
                }
            }

            columns = columns.OrderBy(e => e.Sort).ToList();
            columnDataDic.TryAdd(key, columns);

            return columns;
        }

        /// <summary>
        /// 是否是忽略的列，true：忽略
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private static bool IgnoreProp(string name)
        {
            var r = false;//不忽略
            r = ignoreColumn.Any(x => x == name);
            if (r)//忽略
                return r;
            if (ignoreColumnLike.Length > 0)
            {
                foreach (var item in ignoreColumnLike)
                {
                    //if (item.ToLower() == "id" && EnableReturnId) return r; //启用返回Id列头
                    r = name.EndsWith(item, StringComparison.OrdinalIgnoreCase);
                    //r = name.Contains(item, StringComparison.OrdinalIgnoreCase);
                    if (r) return r;
                }
            }
            return r;
        }

        private static ColumnDataModel CreateColumnData(PropertyInfo item, string lable = "", TableHeadAttribute? tattribute = null)
        {
            int sort = 100;
            int isShow = 1;
            if (tattribute != null)
            {
                sort = tattribute.Sort;
                isShow = tattribute.IsShow;
                lable = tattribute.Description;
            }

            if (lable != null) lable = lable.Replace("Id", "").Replace("ID", "").Replace("id", "");

            var s = item.Name.First().ToString().ToLower() + item.Name.Substring(1);//把首字母变成小写

            var column = new ColumnDataModel
            {
                Lable = lable,
                Property = s,
                Sort = sort,
                IsShow = isShow,
            };
            return column;
        }

        private static string BuildOrderBy<TEntity>(IDictionary<string, object> param) where TEntity : Entity<TEntity>, new()
        {
            string orderBy = null;

            if (param.TryGetValue("OrderBy", out var _orderBy))
            {
                orderBy = BuildOrderBy<TEntity>(_orderBy?.ToString()!);
                param.Remove("OrderBy");
            }
            return orderBy;
        }

        /// <summary>
        /// 查询所有数据 不分页
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        public static string BuildOrderBy<TEntity>(string orderBy = null) where TEntity : Entity<TEntity>, new()
        {
            //if (orderBy.IsNullOrEmpty())
            if (NewLife.StringHelper.IsNullOrEmpty(orderBy))
            {
                return null;
            }
            string _orderBy = null;
            var temps = orderBy.ToLower().Trim().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in temps)
            {
                var temps2 = item.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                var fildName = temps2[0];
                var field = Entity<TEntity>.Meta.Table.FindByName(fildName);
                if (string.IsNullOrEmpty(field)) continue; //如果参数名称 不是表中的字段名称 将忽略
                if (string.IsNullOrEmpty(field.ColumnName)) continue;//如果参数名称 不是表中的字段名称 将忽略

                if (temps2.Length == 2 && temps2[1] != "asc" && temps2[1] != "desc") continue;
                if (temps2.Length > 2)
                    continue; //格式不对
                if (temps.Length > 1)
                {
                    _orderBy += item + ","; //格式正确，拼接到排序字段中
                }
                else
                {
                    _orderBy += item; //格式正确，拼接到排序字段中
                }
            }
            //if (_orderBy.IsNullOrWhiteSpace())
            if (System.String.IsNullOrWhiteSpace(_orderBy))
            {
                var field = Entity<TEntity>.Meta.Table.FindByName("id");
                if (!string.IsNullOrEmpty(field))
                    _orderBy += ",id desc ";
            }
            return _orderBy.TrimEnd(',');
        }

        /// <summary>
        /// 默认的排序
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="p"></param>
        /// <returns></returns>
        public static string BuildDefaultOrderBy<TEntity>() where TEntity : Entity<TEntity>, new()
        {
            string _orderBy = null;

            var fields = Entity<TEntity>.Meta.Table.PrimaryKeys;

            if (fields.Length > 0)
            {
                foreach (var item in fields)
                {
                    _orderBy += $"{item.ColumnName} desc ,";
                }
                _orderBy = _orderBy.Substring(0, _orderBy.Length - 1);

                //if (string.IsNullOrEmpty(_orderBy))
                //{
                //    var field = Entity<TEntity>.Meta.Table.FindByName("id");
                //    if (!string.IsNullOrEmpty(field))
                //    {
                //        _orderBy += "id desc ";
                //    }
                //}
            }
            else
            {
                throw new Exception($"默认的排序 BuildDefaultOrderBy 表[{Entity<TEntity>.Meta.Table.TableName}]没有设置主键,必须设置主键。 ");
            }

            return _orderBy;
        }

        /// <summary>
        /// 获取 Model对象 的属性转换成 列头
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <returns></returns>
        public static string GetSelectColumn<TEntity, TModel>() where TModel : class where TEntity : Entity<TEntity>, new()
        {
            Type type = typeof(TModel);
            Type etype = typeof(TEntity);

            var key = $"{etype.FullName}_{type.FullName}";
            string select = null;

            var r = selectDic.TryGetValue(key, out select);

            if (r && select.IsNotNullAndWhiteSpace())
                return select;

            var infos = type.GetProperties();

            var list = new HashSet<string>();

            foreach (var item in infos)
            {
                var field = Entity<TEntity>.Meta.AllFields.Find(x => x.Column?.Name! == item.Name);

                if (field == null) continue;

                list.Add(field.Column.Name);
            }

            select = list.CombineToString(",");
            selectDic.TryAdd(key, select);

            return select;
        }

        /// <summary>
        /// 获取 数据库实体对象 所有的列
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public static IDataColumn[] GetEntityDataColumn<TEntity>() where TEntity : Entity<TEntity>, new()
        {
            var fields = Entity<TEntity>.Meta.Fields;
            var dataColumn = new IDataColumn[fields.Length];

            for (int i = 0; i < fields.Length; i++)
            {
                dataColumn[i] = fields[i].Field;
            }

            return dataColumn;
        }

        /// <summary>
        /// 获取数据库实体对象,忽略 指定字段和传入的列
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public static IDataColumn[] GetEntitDataIgnoreColumn<TEntity>(IEnumerable<string> incoming = null) where TEntity : Entity<TEntity>, new()
        {
            var ignoreColumn = new string[] { CommonColumns.CreateBy, CommonColumns.CreateTime };
            var mergedArray = ignoreColumn.Concat(incoming).ToArray();

            var fields = Entity<TEntity>.Meta.Fields.Where(s => !mergedArray.Contains(s.ColumnName)).ToArray();

            var dataColumn = new IDataColumn[fields.Length];

            for (int i = 0; i < fields.Length; i++)
            {
                dataColumn[i] = fields[i].Field;
            }

            return dataColumn;
        }

        //SetNoDirtyItem(fs, entity, CommonColumns.C UpdateTime, TimerX.Now);

        public static readonly ConcurrentDictionary<Type, FieldItem[]> _fields = new ConcurrentDictionary<Type, FieldItem[]>();

        ///// <summary>提前设置字段，加速初始化过程</summary>
        ///// <param name="entityType"></param>
        ///// <param name="fields"></param>
        //public static void SetFields(Type entityType, FieldItem[] fields) => _fields.TryAdd(entityType, fields);

        /// <summary>
        /// 根据字段排序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="select"></param>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, string orderBy) where T : class
        {
            if (string.IsNullOrWhiteSpace(orderBy)) throw new ArgumentNullException($"参数 orderBy 为空.");
            string _order = "";
            var a = orderBy.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var prop = a[0];
            if (a.Length == 2)
            {
                _order = a[1];
            }
            // 动态构建排序表达式
            System.Linq.Expressions.ParameterExpression parameter = System.Linq.Expressions.Expression.Parameter(typeof(T), "p");
            System.Linq.Expressions.MemberExpression member = System.Linq.Expressions.Expression.Property(parameter, prop);
            System.Linq.Expressions.LambdaExpression lambda = System.Linq.Expressions.Expression.Lambda(member, parameter);
            System.Linq.Expressions.Expression<Func<T, decimal>> sortExpression = System.Linq.Expressions.Expression.Lambda<Func<T, decimal>>(lambda.Body, lambda.Parameters);
            if (_order.ToLower() == "desc")//倒叙排序
                return list.AsQueryable().OrderByDescending(sortExpression);
            else
                // 假设我们在这里只是为了演示，并且知道属性是 int 类型：
                return list.AsQueryable().OrderBy(sortExpression.Compile());
        }


        /// <summary>
        ///   [JsonField]的属性 判断dto是否有这个属性 Determines if the DTO has any properties marked with [JsonField] attribute
        /// </summary>
        /// <param name="dto">The DTO to inspect</param>
        /// <returns>True if at least one [JsonField] attribute exists with a FieldName specified</returns>
        public static bool IsJsonField<TModel>(TModel dto)
        {
            if (dto == null) throw new ArgumentNullException(nameof(dto));
            return dto.GetType()
                      .GetProperties()
                      .Any(p => p.GetCustomAttribute<JsonFieldAttribute>()?.FieldName != null);
        }

        /// <summary>
        /// 序列化处理，处理dto对象,JOSN转string entity 保存到数据库 
        /// Serializes properties marked with [JsonField] attribute from DTO to JSON strings in the entity
        /// </summary>
        /// <param name="entity">Target entity where JSON strings will be stored</param>
        /// <param name="dto">Source DTO containing properties to serialize</param>
        public static void LoadFieldsJsonCovertString<TEntity, TModel>(TEntity entity, TModel dto)
        {
            if (entity == null) throw new ArgumentNullException(nameof(entity));
            if (dto == null) throw new ArgumentNullException(nameof(dto));

            var dtoType = dto.GetType();
            var entityType = entity.GetType();

            // Cache property lookups to improve performance
            var jsonProperties = dtoType.GetProperties().Select(p => new
            {
                Property = p,
                Attribute = p.GetCustomAttribute<JsonFieldAttribute>()
            })
            .Where(x => x.Attribute != null);
            foreach (var item in jsonProperties)
            {
                try
                {
                    var fieldName = item.Attribute.FieldName ?? item.Property.Name;
                    // Get the value from DTO property
                    var dynamicValue = item.Property.GetValue(dto);
                    // Serialize to JSON if not null
                    var jsonValue = dynamicValue != null
                        ? JsonConvert.SerializeObject(dynamicValue)
                        : null;
                    // Find and set the corresponding property on the entity
                    var entityProperty = entityType.GetProperty(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    entityProperty?.SetValue(entity, jsonValue);

                }
                catch (Exception ex)
                {
                    // Consider logging the error here
                    throw new InvalidOperationException(
                        $"Failed to process JSON field {item.Property.Name}", ex);
                }
            }
        }

        /// <summary>
        /// 反序列化处理,string 转 JOSN输出dto对象  
        /// Deserializes JSON strings from entity to objects in DTO for properties marked with [JsonField]
        /// </summary>
        /// <param name="entity">Source entity containing JSON strings</param>
        /// <param name="dto">Target DTO where deserialized objects will be stored</param>
        public static void LoadFieldsStringCovertJson<TEntity, TModel>(TEntity entity, TModel dto)
        {
            if (entity == null) throw new ArgumentNullException(nameof(entity));
            if (dto == null) throw new ArgumentNullException(nameof(dto));

            var dtoType = dto.GetType();
            var entityType = entity.GetType();

            // Cache property lookups to improve performance
            var jsonProperties = dtoType.GetProperties()
                .Select(p => new
                {
                    Property = p,
                    Attribute = p.GetCustomAttribute<JsonFieldAttribute>()
                })
                .Where(x => x.Attribute != null);

            foreach (var item in jsonProperties)
            {
                try
                {
                    // Determine source field name (use attribute value or property name)
                    var fieldName = item.Attribute.FieldName ?? item.Property.Name;
                    // Get the JSON string from entity property
                    var entityProperty = entityType.GetProperty(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                    var jsonValue = entityProperty?.GetValue(entity) as string;
                    // Deserialize to object if not null/empty
                    if (!string.IsNullOrEmpty(jsonValue))
                    {
                        var targetType = item.Property.PropertyType;
                        var deserializedValue = JsonConvert.DeserializeObject(jsonValue, targetType);
                        item.Property.SetValue(dto, deserializedValue);
                    }
                    else
                    {
                        item.Property.SetValue(dto, null);
                    }
                }
                catch (Exception ex)
                {
                    // Consider logging the error here
                    throw new InvalidOperationException($"Failed to reverse process JSON field {item.Property.Name}", ex);
                }
            }
        }

    }
}